using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Markup;

namespace dingtalk_card_table
{
    [Icon("pack://application:,,,/dingtalk_card_table;component/Resources/Icon.png")]
    [Designer("dingtalk_card_table.Designer.dingtalk_card_tableServerCommandDesigner, dingtalk_card_table")]
    public class dingtalk_card_tableServerCommand : Command, ICommandExecutableInServerSideAsync
    {
        public shujuleibie 数据类型 { get; set; }
        public enum shujuleibie
        {
            [Description("下拉选项数组")]
            xialashuzu,
            [Description("表格")]
            Table,
            [Description("表单")]
            Form,
            [Description("图表")]
            Chart,
            [Description("用户信息")]
            UserInfo
        }

        [FormulaProperty] public object 参数值 { get; set; }
        [FormulaProperty] public object 表格参数值 { get; set; }
       
        [Description("勾选则为显示表格行头。")]
        [DefaultValue(false)] public bool 是否显示行头 { get; set; } = false;

        [Description("有多少列则添加多少个列表数据来表达对应的列设置。")]
        [ListProperty] public List<kuozhan> 表格列设置选项 { get; set; }

        // 等于时则可见
        public override bool GetDesignerPropertyVisible(string propertyName, CommandScope commandScope)
        {
            if (propertyName == nameof(是否显示行头) || propertyName == nameof(表格列设置选项) || propertyName == nameof(表格参数值))
            {
                return this.数据类型 == shujuleibie.Table;
            }
            if (propertyName == nameof(参数值))
            {
                return this.数据类型 == shujuleibie.xialashuzu;
            }

            return base.GetDesignerPropertyVisible(propertyName, commandScope);
        }

        [ResultToProperty]
        [DisplayName("返回结果")]
        public string ResultTo { get; set; } = "返回结果";

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            string value = null;
            //先计算后判断
            var value1 = await dataContext.EvaluateFormulaAsync(参数值);
            var 数据类别 = 数据类型;
            //value1 is ArrayList ||
            if (数据类别 == shujuleibie.xialashuzu)
            {
                value = JsonConvert.SerializeObject(value1, Formatting.Indented);
                dataContext.Parameters[ResultTo] = value;  // 把计算的结果设置到结果变量中
            }
            if (数据类别 == shujuleibie.Table)
            {
                var value2 = await dataContext.EvaluateFormulaAsync(表格参数值);
                if (value2 is List<Dictionary<string, object>> listdata)
                {
                    var aa01 = await biaogechuli(dataContext, listdata, 表格列设置选项, 是否显示行头);
                    dataContext.Parameters[ResultTo] = aa01;  // 把计算的结果设置到结果变量中
                }
                else
                {
                    return new ExecuteResult() { ErrCode = 101, Message = "你提交的数据格式不正确，要求是对象数组类型" };
                }
                
            }
            else
            {
                value = (await dataContext.EvaluateFormulaAsync(参数值))?.ToString() ?? string.Empty;
                dataContext.Parameters[ResultTo] = value;  // 把计算的结果设置到结果变量中
            }

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "钉钉互动卡片数据格式转换";
        }
        // 表格设置选项
        public class kuozhan : ObjectPropertyBase
        {
            [FormulaProperty] public object 显示列名 { get; set; }
            public lieleixing 列数据类型 { get; set; }
            [IntProperty(Min = 1, Max = 100)]
            public int 列宽百分比 { get; set; }
        }

        public enum lieleixing
        {
            [Description("文本")]
            STRING,
            [Description("应用名")]
            MICROAPP,
            [Description("应用介绍")]
            OBJECT
        }

        //处理表格数据
        public static async Task<object> biaogechuli (IServerCommandExecuteContext dataContext, List<Dictionary<string, object>> aaa, List<kuozhan> bbb, bool ddd )
        {
   
            var meta = new List<object>();
            var data = new List<object>();
            var columnNames = new List<string>();//记录列名
            int n = 1;
            //处理行数据
            foreach (var item2 in aaa) //对传入的对象数组取对象名及对象值
            {
                if (ddd) //是否显示行头
                { 
                    var aa01 = new Dictionary<string, object>();
                    // 遍历字典的键值对
                    foreach (var kvp in item2)
                    {
                        aa01["rank"]= n;
                        string key = kvp.Key; //取对象名
                        // 添加列名到记录列表
                        if (!columnNames.Contains(key)) // 检查是否已存在
                        {
                            columnNames.Add(key); // 添加唯一的列名
                        }
                        string value = kvp.Value?.ToString() ?? string.Empty;//取对象值
                        aa01[key] = value;
                    }
                    data.Add(aa01); // 将 aa01 添加到 data 列表
                }
                else
                {
                    var aa01 = new Dictionary<string, string>();
                    // 遍历字典的键值对
                    foreach (var kvp in item2)
                    {
                        string key = kvp.Key;

                        // 添加列名到记录列表
                        if (!columnNames.Contains(key)) // 检查是否已存在
                        {
                            columnNames.Add(key); // 添加唯一的列名
                        }

                        string value = kvp.Value?.ToString() ?? string.Empty;
                        aa01[key] = value;
                    }
                    data.Add(aa01); // 将 aa01 添加到 data 列表
                }
                n++;//对行数据进行个数计算
            }

            // 第二次循环 bbb，构建 meta 用于对应列名取值
            int i = 0;

            //处理列数据
            if (ddd) //是否显示行头
            {
                var emptyData = new Dictionary<string, object> //创建一个空对象
                    {
                        { "aliasName", "" },
                        { "alias", "rank" },
                        { "dataType", "STRING" },
                        { "weight", 10 }
                    };
                meta.Add(emptyData);
            }
            foreach (var item1 in bbb)//循环列设置 有多少列设置多少个数组
            {
                string shujuleixing = item1.列数据类型.ToString();
                string xianshilieming = (await dataContext.EvaluateFormulaAsync(item1.显示列名))?.ToString() ?? string.Empty;
                var emptyData = new Dictionary<string, object> //创建一个空对象
                    {
                        { "aliasName", xianshilieming },
                        { "alias", columnNames[i] },
                        { "dataType", shujuleixing },
                        { "weight", item1.列宽百分比 }
                    };
                meta.Add(emptyData);
                i++; // 确保索引 i 在循环中正确递增
            }
            var result = new
            {
                data = data,
                meta = meta
            };

            return result;
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }
}
